package api

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
)

type ApiController struct {
}

func (api ApiController) Test(c *gin.Context) {
	// 设置cookie
	c.SetCookie("username", "张三", 3600, "/", "localhost", false, true)
	c.JSON(http.StatusOK, gin.H{
		"age":      c.DefaultQuery("age", "18"),
		"username": c.Query("username"),
	})
}

func (api ApiController) Html(c *gin.Context) {
	c.HTML(http.StatusOK, "default/users.html", gin.H{})
}

func (api ApiController) Ping(c *gin.Context) {
	// 获取cookie
	username, _ := c.Cookie("username")
	fmt.Println(username)
	c.String(http.StatusOK, "cookie="+username)
	//c.HTML(http.StatusOK, "default/users.html", gin.H{})
}

func (api ApiController) DeleteCookie(c *gin.Context) {
	// 获取cookie
	c.SetCookie("username", "张三", -1, "/", "localhost", false, true)
	c.String(http.StatusOK, "删除成功")
}

func (api ApiController) SetSession(c *gin.Context) {
	// 获取cookie
	session := sessions.Default(c)
	session.Options(sessions.Options{MaxAge: 3600 * 6}) // 6h 过期
	session.Set("username", "张三 111")
	session.Save()
	c.String(http.StatusOK, "设置成功")
}

func (api ApiController) GetSession(c *gin.Context) {
	// 获取cookie
	session := sessions.Default(c)
	value := session.Get("username")
	fmt.Println(value)
	c.String(http.StatusOK, "session=%v", value)
}
